package com.syezon.wifikey.ad;

import android.app.Activity;
import android.util.Log;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.hodanet.appadvplatclient.AdvClient;
import com.hodanet.appadvplatclient.ad.AdInfo;
import com.hodanet.appadvplatclient.api.BaseResult;
import com.hodanet.appadvplatclient.config.Config;
import com.syezon.android.base.netstatus.NetChangeObserver;
import com.syezon.android.base.netstatus.NetStateReceiver;
import com.syezon.android.base.netstatus.NetUtils;
import com.syezon.android.base.utils.ActivityUtils;
import com.syezon.wifikey.ad.config.ConfigNewAdObserver;
import com.syezon.wifikey.ad.config.ConfigObserver;
import com.syezon.wifikey.channel.ChannelConfig;
import com.syezon.wifikey.config.AppConfig;
import com.syezon.wifikey.config.AppOptConfig;
import com.syezon.wifikey.config.HomeConfig;
import com.syezon.wifikey.splash.SplashActivity;
import com.syezon.wifikey.splash.config.FrontAdConfig;
import com.syezon.wifikey.splash.config.SplashConfig;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.schedulers.Schedulers;


public class ConfigService {

    private static volatile ConfigService instance;
    private static List<ConfigObserver> selfAdConfigObservers = new ArrayList<>();
    private static List<ConfigObserver> gdtAdConfigObservers = new ArrayList<>();
    private static List<ConfigObserver> csjAdConfigObservers = new ArrayList<>();
    private static List<ConfigNewAdObserver> newAdConfigObservers = new ArrayList<>();
    private boolean showAd;
    private boolean showGDTAd = true;
    private boolean showCSJAd = true;
    private boolean showSelfAd = true;
    private boolean showKYAd = true;
    private boolean showYiYouLiaoNewsAd = false;

    private AdNetChangeObserver adNetChangeObserver = new AdNetChangeObserver();

    private ConfigService() {
        NetStateReceiver.registerObserver(adNetChangeObserver);
    }

    public static ConfigService getInstance() {
        if (instance == null) {
            synchronized (ConfigService.class) {
                if (instance == null) {
                    instance = new ConfigService();
                }
            }
        }
        return instance;
    }

    public void reset() {
        showAd = false;
        showSelfAd = true;
        showGDTAd = true;
        showCSJAd = true;
        showYiYouLiaoNewsAd = false;
        selfAdConfigObservers.clear();
        gdtAdConfigObservers.clear();
        csjAdConfigObservers.clear();
    }

    public boolean isShowAd() {
        return this.showAd;
    }

    public boolean isShowSelfAd() {
        return showAd && showSelfAd;
    }

    public boolean isShowGDTAd() {
        return showAd && showGDTAd;
    }

    public boolean isShowCSJAd() {
        return showAd && showCSJAd;
    }

    public boolean isShowYiyouLiaoNewsAd() {
        return showAd && showYiYouLiaoNewsAd;
    }

    public void registerObserver(ConfigObserver observer) {
        if (observer != null && !selfAdConfigObservers.contains(observer)) {
            selfAdConfigObservers.add(observer);
            //TODO 广告可能自有和联盟广告，所以这里根据是否有广告来显示，如果没有自有，自行过滤
            observer.onChange(showAd);
        }
    }

    public void registerGDTObserver(ConfigObserver observer) {
        if (observer != null && !gdtAdConfigObservers.contains(observer)) {
            gdtAdConfigObservers.add(observer);
            observer.onChange(showAd && showGDTAd);
        }
    }

    public void registerCSJObserver(ConfigObserver observer) {
        if (observer != null && !csjAdConfigObservers.contains(observer)) {
            csjAdConfigObservers.add(observer);
            observer.onChange(showAd && showCSJAd);
        }
    }

    public void registerNewAdObserver(ConfigNewAdObserver observer) {
        if (observer != null && !newAdConfigObservers.contains(observer)) {
            newAdConfigObservers.add(observer);
        }
    }

    public void unRegisterNewObserver(ConfigNewAdObserver observer) {
        if (newAdConfigObservers.contains(observer)) {
            newAdConfigObservers.remove(observer);
        }
    }

    public void unRegisterObserver(ConfigObserver observer) {
        if (selfAdConfigObservers.contains(observer)) {
            selfAdConfigObservers.remove(observer);
        }
    }

    public void unRegisterGDTObserver(ConfigObserver observer) {
        if (gdtAdConfigObservers.contains(observer)) {
            gdtAdConfigObservers.remove(observer);
        }
    }

    public void unRegisterCSJObserver(ConfigObserver observer) {
        if (csjAdConfigObservers.contains(observer)) {
            csjAdConfigObservers.remove(observer);
        }
    }

    private void notifyConfigChange() {
        if (!selfAdConfigObservers.isEmpty()) {
            int size = selfAdConfigObservers.size();
            for (int i = 0; i < size; i++) {
                ConfigObserver configObserver = selfAdConfigObservers.get(i);
                if (configObserver != null) {
                    configObserver.onChange(showAd);
                }
            }
        }

        if (!gdtAdConfigObservers.isEmpty()) {
            int size = gdtAdConfigObservers.size();
            for (int i = 0; i < size; i++) {
                ConfigObserver configObserver = gdtAdConfigObservers.get(i);
                if (configObserver != null) {
                    configObserver.onChange(showAd && showGDTAd);
                }
            }
        }

        if (!csjAdConfigObservers.isEmpty()) {
            int size = csjAdConfigObservers.size();
            for (int i = 0; i < size; i++) {
                ConfigObserver configObserver = csjAdConfigObservers.get(i);
                if (configObserver != null) {
                    configObserver.onChange(showAd && showCSJAd);
                }
            }
        }
    }

    public void configOpt(BaseResult<List<Config>> listBaseResult) {
        int gdtSwitchInt = 0;
        int optAdSrc = 0;
        int ttSDk = 0;
        int splashAdSource = 0;
        int frontAdSource = 0;
        if (listBaseResult != null && listBaseResult.getData() != null) {
            List<Config> configList = listBaseResult.getData();
            for (int i = 0; configList != null && i < configList.size(); i++) {
                Config config = configList.get(i);
                int ver = config.getVer();
                Properties properties = config.getProperties();
                String channel = ChannelConfig.getChannel();
                String configChannel = config.getChannel();
                if (configChannel.equals(channel)) {
                    int adSwitchInt = 1;
                    int showSelfAdInt = 1;
                    int showGDTAdInt = 1;
                    int showCSJAdInt = 1;
                    int showKYAdInt = 1;
                    int adGapInt = 0;
                    String showSelfAdStr = properties.getProperty("SWITCH_ZY", "1");
                    try {
                        showSelfAdInt = Integer.parseInt(showSelfAdStr);
                    } catch (Exception e) {
                        showSelfAdInt = 1;
                    }
                    String showGDTAdStr = properties.getProperty("SWITCH_GDT", "1");
                    try {
                        showGDTAdInt = Integer.parseInt(showGDTAdStr);
                    } catch (Exception e) {
                        showGDTAdInt = 1;
                    }
                    String showCSJAdStr = properties.getProperty("SWITCH_CSJ", "1");
                    try {
                        showCSJAdInt = Integer.parseInt(showCSJAdStr);
                    } catch (Exception e) {
                        showCSJAdInt = 1;
                    }
                    String showKYAdStr = properties.getProperty("SWITCH_KY", "1");
                    try {
                        showKYAdInt = Integer.parseInt(showKYAdStr);
                    } catch (Exception e) {
                        showKYAdInt = 1;
                    }
                    String adGap = properties.getProperty("AD_GAP", "0");
                    try {
                        adGapInt = Integer.parseInt(adGap);
                    } catch (Exception e) {
                        adGapInt = 0;
                    }
                    SplashConfig.saveYiYouLiaoNewsAdCount(adGapInt);
                    String splashAdSourceStr = properties.getProperty("SWITCH_KP", "0");
                    try {
                        splashAdSource = Integer.parseInt(splashAdSourceStr);
                    } catch (Exception e) {
                        splashAdSource = 0;
                    }
                    String frontAdSourceStr = properties.getProperty("SWITCH_QT", "0");
                    try {
                        frontAdSource = Integer.parseInt(frontAdSourceStr);
                    } catch (Exception e) {
                        frontAdSource = 0;
                    }
//                                    String splashOrder = properties.getProperty("SWITCH_OPEN", SplashConfig.DEFAULT_SPLASH_AD_ORDER);
//                                    SplashConfig.saveSplashAdOrder(splashOrder);

                    String splashOrder = properties.getProperty("SWITCH_SPLASH", SplashConfig.DEFAULT_SPLASH_AD_ORDER);
                    SplashConfig.saveSplashAdOrder(splashOrder);

//                                    String rewardVideoOrder = properties.getProperty("SWITCH_VIDEO", OptVideoAdConfig.DEFAULT_INTER_AD_ORDER);
//                                    OptVideoAdConfig.saveVideoAdOrder(rewardVideoOrder);

//                    String rewardVideoOrder = properties.getProperty("SWITCH_INSPIRE", OptVideoAdConfig.DEFAULT_VIDEO_AD_ORDER);
//                    OptVideoAdConfig.saveVideoAdOrder(rewardVideoOrder);

                    String interAdOrder = properties.getProperty("SWITCH_TABLE", IntAdConfig.DEFAULT_INTER_AD_ORDER);
                    IntAdConfig.saveInterAdOrder(interAdOrder);

                    String show_news_tab = properties.getProperty("SHOW_NEWS_TAB", "1");
                    int showNewsTabInt = 1;
                    try {
                        showNewsTabInt = Integer.parseInt(show_news_tab);
                        Log.d("newsTab",show_news_tab);
                    } catch (Exception e) {

                    }
                    if (showNewsTabInt == 1) {
                        AppConfig.saveShowNewsTab(true);
                    } else {
                        AppConfig.saveShowNewsTab(false);
                    }
                    if (ver <= AppUtils.getAppVersionCode()) {
                        String adSwitch = properties.getProperty("SWITCH", "1");
                        try {
                            adSwitchInt = Integer.parseInt(adSwitch);
                        } catch (Exception e) {
                            adSwitchInt = 0;
                        }
                    } else {
                        showSelfAdInt = 1;
                        showGDTAdInt = 1;
                        showCSJAdInt = 1;
                    }
                    if (showSelfAdInt == 1) {
                        showSelfAd = true;
                    } else {
                        showSelfAd = false;
                    }

                    showYiYouLiaoNewsAd = (adGapInt != 0);

                    if (showGDTAdInt == 1) {
                        showGDTAd = true;
                    } else {
                        showGDTAd = false;
                    }
                    if (showCSJAdInt == 1) {
                        showCSJAd = true;
                    } else {
                        showCSJAd = false;
                    }
                    if (showKYAdInt == 1) {
                        showKYAd = true;
                    } else {
                        showKYAd = false;
                    }
                    String gdtSwitch = properties.getProperty("THIRDAD", "0");
                    try {
                        gdtSwitchInt = Integer.parseInt(gdtSwitch);
                    } catch (Exception e) {
                        gdtSwitchInt = 0;
                    }
                    String opt_ad_src = properties.getProperty("OPT_AD_SRC", "0");
                    try {
                        optAdSrc = Integer.parseInt(opt_ad_src);
                    } catch (Exception e) {
                        optAdSrc = 0;
                    }
                    String tt_sdk = properties.getProperty("TT_SDK", "0");
                    try {
                        ttSDk = Integer.parseInt(tt_sdk);
                    } catch (Exception e) {
                        ttSDk = 0;
                    }
                    if (adSwitchInt == 1) {
                        showAd = true;
                    }
                    break;
                }
            }
        }
        if (showAd) {
            if (optAdSrc == 1) {
                if (showGDTAd) {
                    AppOptConfig.saveOptAdSource(AppOptConfig.OPT_AD_GDT);
                } else {
                    AppOptConfig.saveOptAdSource(AppOptConfig.OPT_AD_SELF);
                }
            } else if (optAdSrc == 2) {
                AppOptConfig.saveOptAdSource(AppOptConfig.OPT_AD_BD);
            } else if (optAdSrc == 3) {
                if (showCSJAd) {
                    AppOptConfig.saveOptAdSource(AppOptConfig.OPT_AD_TT);
                } else {
                    AppOptConfig.saveOptAdSource(AppOptConfig.OPT_AD_SELF);
                }
            } else {
                AppOptConfig.saveOptAdSource(AppOptConfig.OPT_AD_SELF);
            }
            if (ttSDk == 1) {
                HomeConfig.saveOptOverAdSource(HomeConfig.OPT_OVER_AD_SOURCE_TT);
            } else {
                HomeConfig.saveOptOverAdSource(HomeConfig.OPT_OVER_AD_SOURCE_NONE);
            }
        } else {
            AppOptConfig.saveOptAdSource(AppOptConfig.OPT_AD_SELF);
        }
        if (showAd && showGDTAd) {
            AdConfig.saveCanShowGDTAd(true);
        } else {
            AdConfig.saveCanShowGDTAd(false);
        }
        if (showAd && showCSJAd) {
            AdConfig.saveCanShowCSJAd(true);
        } else {
            AdConfig.saveCanShowCSJAd(false);
        }
        if (showAd && showSelfAd) {
            AdConfig.saveCanShowSelfAd(true);
        } else {
            AdConfig.saveCanShowSelfAd(false);
        }
        if (showAd && showKYAd) {
            AdConfig.saveCanShowKYAd(true);
        } else {
            AdConfig.saveCanShowKYAd(false);
        }

        if (showAd && showYiYouLiaoNewsAd) {
            AdConfig.saveCanShowYiYouLiaoAd(true);
        } else {
            AdConfig.saveCanShowYiYouLiaoAd(false);
        }

        if (showAd) {
            FrontAdConfig.saveCanShowAd(true);
        } else {
            FrontAdConfig.saveCanShowAd(false);
        }
        notifyConfigChange();
    }

    public void getAds() {
        Observable.create(new ObservableOnSubscribe<BaseResult<List<AdInfo>>>() {
            @Override
            public void subscribe(ObservableEmitter<BaseResult<List<AdInfo>>> e) throws Exception {
                BaseResult<List<AdInfo>> advs = AdvClient.getInstance().getNewAdvs(AdPositionEnum.SPLASH.getPosId(), ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                e.onNext(advs);
            }
        }).subscribeOn(Schedulers.io())
                .subscribe(new Observer<BaseResult<List<AdInfo>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResult<List<AdInfo>> listBaseResult) {
                        if (listBaseResult == null) {
                            notifyNewAdConfigChange(null);
                        } else {
                            notifyNewAdConfigChange(listBaseResult.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void getConfig() {
        Observable<BaseResult<List<Config>>> optResultAd1 = Observable.create(new ObservableOnSubscribe<BaseResult<List<Config>>>() {
            @Override
            public void subscribe(ObservableEmitter<BaseResult<List<Config>>> e) throws Exception {
                BaseResult<List<Config>> config = AdvClient.getInstance().getConfig(ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                e.onNext(config);
            }
        });

        Observable<BaseResult<List<AdInfo>>> optResultAd2 = Observable.create(new ObservableOnSubscribe<BaseResult<List<AdInfo>>>() {
            @Override
            public void subscribe(ObservableEmitter<BaseResult<List<AdInfo>>> e) throws Exception {
                BaseResult<List<AdInfo>> advs = AdvClient.getInstance().getNewAdvs(AdPositionEnum.SPLASH.getPosId(), ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                e.onNext(advs);
            }
        });

        Observable.zip(optResultAd1, optResultAd2, new BiFunction<BaseResult<List<Config>>, BaseResult<List<AdInfo>>, BaseResult<List<AdInfo>>>() {

            @Override
            public BaseResult<List<AdInfo>> apply(BaseResult<List<Config>> listBaseResult, BaseResult<List<AdInfo>> listBaseResult2) throws Exception {
                configOpt(listBaseResult);
                return listBaseResult2;
            }
        }).subscribeOn(Schedulers.io())
                .subscribe(new Observer<BaseResult<List<AdInfo>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResult<List<AdInfo>> optAdInfo) {
                        LogUtils.e("陈超      onNext");
                        if (optAdInfo == null) {
                            notifyNewAdConfigChange(null);
                        } else {
                            notifyNewAdConfigChange(optAdInfo.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e("configService" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        LogUtils.e("陈超      onComplete");
                    }
                });

    }

    private class AdNetChangeObserver extends NetChangeObserver {
        @Override
        public void onNetConnected(NetUtils.NetType type) {
            super.onNetConnected(type);
            if (type == NetUtils.NetType.WIFI) {
                Activity topActivity = ActivityUtils.getTopActivity();
                if (topActivity != null && topActivity.getClass() != SplashActivity.class) {
                    getConfig();
                }
            }
        }
    }

    public void notifyNewAdConfigChange(List<AdInfo> adInfos) {
        if (!newAdConfigObservers.isEmpty()) {
            int size = newAdConfigObservers.size();
            for (int i = 0; i < size; i++) {
                ConfigNewAdObserver configObserver = newAdConfigObservers.get(i);
                configObserver.onChange(adInfos);
            }
        }
    }
}
